﻿using System.Collections.Generic;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using UnityEditor;
using UnityEngine;

namespace BearUtil
{
    /// <summary>
    /// 全局对话设置，向下继承
    /// </summary>
    public class StoriesSetting : GlobalConfig<StoriesSetting>, ICustomSetting
    {
        public const string MenuName = "故事";
        public List<SeriesHandle> Series = new List<SeriesHandle>();
        
        public string AddName
        {
            get { return "新增系列"; }
        }

        public string RemoveName
        {
            get { return "无"; }
        }

        /// <summary>
        /// Add new Series
        /// </summary>
        public void Add(OdinMenuEditorWindow window)
        {
            if (Series == null)
                Series = new List<SeriesHandle>();
            Series.Clear();

            RightClickMenuItemsCreator.ShowDialog<SeriesHandle>("Assets/StoryEditor/Graph/Series", (obj) =>
            {
                Series.Add(obj);
                obj.SeriesName = obj.name;
                window.TrySelectMenuItemWithObject(obj);
            });
            
            AssetDatabase.Refresh();
        }

        /// <summary>
        ///  Remove Story Data
        /// </summary>
        public void Remove(OdinMenuItem selected)
        {
            // // delete data 
            // if (selected == null)
            // {
            //     Debug.LogWarning("未找到删除对象");
            //     return;
            // }
            //
            // (selected.Value as SeriesHandle)?.DeleteSelf();
        }

        public SeriesHandle FindSeriesByStoryGraph(StoryGraph storyGraph)
        {
            foreach (var handle in Series)
            {
                var t = handle.Stories.Find(story => story == storyGraph);
                if (t != null)
                    return handle;
            }

            return null;
        }


        [InfoBox("生成 dialogue.xls 文件，记录剧情触发逻辑")]
        [Button("生成 Dialog Excel", ButtonSizes.Large)]
        public void OutputExcel()
        {
            Dictionary<string, List<FormatData>> cache = new Dictionary<string, List<FormatData>>();

            for (var i = 0; i < Series.Count; i++)
            {
                foreach (var storyGraph in Series[i].Stories)
                {
                    var datas = storyGraph.CollectAllFormatData();
                    for (int j = 0; j < datas.Count; j++)
                    {
                        var data = datas[j];
                        var key = data.FileName;
                        if (!cache.ContainsKey(key))
                        {
                            cache.Add(key, new List<FormatData>());
                        }
                        
                        cache[key].Add(data);
                    }
                }
            }
            
            // 综合输出各种 xlsx 
            ExcelDataGenerator.GenerateStoryData(cache);
        }
    }
}